package com.cgs.mongo.extractor;

import com.cgs.mongo.exception.ParserException;
import com.mongodb.client.MongoCursor;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据提取器
 *
 * @param <K> 结果泛型
 */
public interface CursorExtractor<K> {

    /**
     * 从object对象中抽取数据
     * {@link AbstractCursorExtractor}
     *
     * @param result 数据对象(MongoIterable|Long|Document)
     * @return 泛型对象
     */
    K extractData(Object result);


    /**
     * 对迭代器数据进行区分处理
     * 引入RowMapper处理每行数据
     *
     * @param iterator  迭代器
     * @param rowMapper 行处理器
     * @param <T>       泛型
     * @return 泛型对象
     * @throws ParserException
     */
    static <T> List<T> forEach(MongoCursor<Object> iterator, RowMapper<T> rowMapper) throws ParserException {
        List<T> result = new ArrayList<>();
        for (int rowNum = 0; iterator.hasNext(); rowNum++) {
            Object next = iterator.next();
            if (next instanceof Document) {
                result.add(rowMapper.mapRow(BsonDocument.parse(((Document) next).toJson()), rowNum));
            } else if (next instanceof BsonString) {
                result.add(rowMapper.mapRow((new BsonDocument("value", ((BsonString) next))), rowNum));
            } else if (next instanceof BsonDocument) {
                result.add(rowMapper.mapRow(((BsonDocument) next), rowNum));
            } else {
                throw ParserException.instance("无法解析的结果类型：" + next.getClass());
            }
        }
        return result;
    }
}
